package com.shadow.quartz;


import com.shadow.common.entity.ScheduleJobEntity;
import com.shadow.common.exception.RException;
import org.quartz.*;

/**
 * 定时任务工具类.
 * @author: Pbody
 * @date: 2021/3/23 10:20
 */
public final class ScheduleUtils {

    /** 任务调度参数key. **/
    public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";

    /** job前缀. **/
    private static final String JOB_NAME = "TASK_";

    private ScheduleUtils() {
    }

    /**
     * 获取触发器key.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param jobId     任务ID
     * @return void
     **/
    public static TriggerKey getTriggerKey(final String jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobKey.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param jobId     任务ID
     * @return void
     **/
    public static JobKey getJobKey(final String jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler 时间调度对象
     * @param jobId     任务ID
     * @return void
     **/
    public static CronTrigger getCronTrigger(final Scheduler scheduler, final String jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new RException("获取定时任务CronTrigger出现异常", e);
        }
    }

    /**
     * 创建定时任务.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler     时间调度对象
     * @param scheduleJob   任务对象
     **/
    public static void createScheduleJob(final Scheduler scheduler, final ScheduleJobEntity scheduleJob) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class)
                    .withIdentity(getJobKey(scheduleJob.getId())).build();
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId()))
                    .withSchedule(scheduleBuilder).build();
            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JOB_PARAM_KEY, scheduleJob);
            scheduler.scheduleJob(jobDetail, trigger);
            //暂停任务
            if (scheduleJob.getStatus() == 0) {
                pauseJob(scheduler, scheduleJob.getId());
            }
        } catch (SchedulerException e) {
            throw new RException("创建定时任务失败", e);
        }
    }

    /**
     * 更新定时任务.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler     时间调度对象
     * @param scheduleJob   任务对象
     **/
    public static void updateScheduleJob(final Scheduler scheduler, final ScheduleJobEntity scheduleJob) {
        try {
            TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //参数
            trigger.getJobDataMap().put(JOB_PARAM_KEY, scheduleJob);
            scheduler.rescheduleJob(triggerKey, trigger);
            //暂停任务
            if (scheduleJob.getStatus() == 0) {
                pauseJob(scheduler, scheduleJob.getId());
            }
        } catch (SchedulerException e) {
            throw new RException("更新定时任务失败", e);
        }
    }

    /**
     * 立即执行任务.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler         时间调度对象
     * @param scheduleJob     任务对象
     **/
    public static void run(final Scheduler scheduler, final ScheduleJobEntity scheduleJob) {
        try {
            //参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JOB_PARAM_KEY, scheduleJob);
            //执行
            scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap);
        } catch (SchedulerException e) {
            throw new RException("立即执行定时任务失败", e);
        }
    }

    /**
     * 暂停任务.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler 时间调度对象
     * @param jobId     任务ID
     **/
    public static void pauseJob(final Scheduler scheduler, final String jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RException("暂停定时任务失败", e);
        }
    }

    /**
     * 恢复任务.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler 时间调度对象
     * @param jobId     任务ID
     **/
    public static void resumeJob(final Scheduler scheduler, final String jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RException("恢复定时任务失败", e);
        }
    }

    /**
     * 删除定时任务.
     * @author Pbody
     * @date 13:51 2021/3/23
     * @param scheduler 时间调度对象
     * @param jobId     任务ID
     **/
    public static void deleteScheduleJob(final Scheduler scheduler, final String jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RException("删除定时任务失败", e);
        }
    }
}
